const { Sequelize } = require('sequelize');

const {
  SQL_HOST,
  SQL_PORT,
  SQL_USER,
  SQL_PWD,
  SQL_DB,
} = require('../config/config.default');

const sequelize = new Sequelize(SQL_DB, SQL_USER, SQL_PWD, {
  host: SQL_HOST,
  port: SQL_PORT,
  dialect: 'mysql',
  timezone: '+08:00', // 设置时区（中国为东八区）
});

sequelize.addHook('afterSave', 'afterBulkCreate', (instance) => {
  ['createdAt', 'updatedAt', 'deletedAt'].forEach((key) => {
    if (instance.dataValues[key]) {
      const date = new Date(instance.dataValues[key]).toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      });

      instance.dataValues[key] = date.replace(/\//g, '-');
    }
  });
});

try {
  sequelize.authenticate().then(() => {
    console.log(`\x1B[42m 数据库连接成功 \x1B[0m`);
  });
} catch (error) {
  console.log(`\x1B[45m ${error} \x1B[0m`);
}

module.exports = sequelize;
